<template>
  <div class="systemAgent components-container">
	<!--=========头部=========-->
	<div class="searchBar">
	  <fns-header @search="queryList">
      <span slot="slot1">
          <el-form-item label="登录名">
              <el-input v-model="header.loginName" placeholder="请输入登录名" :maxlength="30" clearable></el-input>
          </el-form-item>

          <el-form-item label="租户名称">
              <el-input v-model="header.tenantName" placeholder="请输入租户名称" :maxlength="30" clearable></el-input>
          </el-form-item>
         <el-form-item label="状态">
			<el-select v-model="header.status" placeholder="请选择状态" clearable>
			  <el-option
					  v-for="item in stateOption"
					  :key="item.value"
					  :label="item.label"
					  :value="item.value">
			  </el-option>
			</el-select>
          </el-form-item>
      </span>
	  </fns-header>
	</div>

	<!--=======表格=======-->
	<div class="fns-table-handle mainTable">
	  <div class="btnLine">
		<el-button type="primary" size="medium" class="iconfont icon-xinzeng" @click="updateAndAdd('', 'add')" v-has="'pcadmin_sys_sys_tenant_create'"> 新增</el-button>
	  </div>
	  <fns-table :customerField="customerField">
		<el-table-column
				slot="right"
				label="操作"
				align="center"
				fixed="right"
				width="100">
		  <template slot-scope="scope">
			<el-tooltip content="查看" placement="top"  v-has="'pcadmin_sys_sys_tenant_detail'">
			  <el-button type="mini" icon="iconfont icon-chakan3" @click="updateAndAdd(scope, 'look')"></el-button>
			</el-tooltip>
			<el-tooltip content="修改" placement="top"  v-has="'pcadmin_sys_sys_tenant_update'">
			  <el-button type="mini" icon="iconfont icon-xiugai" @click="updateAndAdd(scope, 'update')"></el-button>
			</el-tooltip>
		  </template>
		</el-table-column>
	  </fns-table>
	  <!-- ========页码======-->
	  <pages v-on:_pageChange="_pageChange" :total="total" :currentPage="page.index"></pages>
	</div>

	<!--=======弹窗=======-->
	<!--新增/修改/查看弹窗-->
	<div v-if="dialogData.dialogVisible">
	  <fns-dialog :dialogData="dialogData" @submitForm="submitForm" width="100%">
		<el-form  id='formModel' ref="formModel" :model="formModel" :rules="rules" label-width="110px"  slot="body" v-loading="loading">
		  <el-row>

			<el-form-item v-if="isLoginName" label="登录名">
			  <el-input v-model="formModel.loginName" :maxlength="16" type="text" placeholder="请输入登录名" disabled></el-input>
			</el-form-item>

			<el-form-item v-else label="登录名" :prop="isValidate ? 'loginName' : ''" >
			  <el-input v-model="formModel.loginName" :maxlength="16" type="text" placeholder="请输入登录名" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			</el-form-item>

			  <el-form-item label="手机号" :prop="isValidate ? 'phone' : ''">
				<el-input v-model="formModel.phone" :maxlength="11" type="text" placeholder="请输入手机号" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

		  </el-row>

		  <el-row>
			  <el-form-item label="租户名称" :prop="isValidate ? 'tenantName' : ''">
				<el-input v-model="formModel.tenantName" :maxlength="50" type="text" placeholder="请输入租户名称" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

			  <el-form-item :offset="1" class="more-text" label="租户负责人" :prop="isValidate ? 'tenantLeader': ''">
				<el-input v-model="formModel.tenantLeader" :maxlength="20" type="text" placeholder="请输入租户负责人" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>
		  </el-row>

		  <el-row>
			  <el-form-item label="密码" :prop="isValidate ? 'password': ''">
				<el-input v-model="formModel.password" :maxlength="16" type="password" placeholder="请输入密码" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>

			  <el-form-item :offset="1" label="确认密码" :prop="isValidate ? 'confirmPsd' : ''">
				<el-input v-model="formModel.confirmPsd" :maxlength="16" type="password" placeholder="请输入密码" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>
		  </el-row>
		  <!--<el-row>-->
			<!--<el-col :span="11">-->
			  <!--<el-form-item label="登录权限：" :prop="isValidate ? 'rules' : ''">-->
				<!--&lt;!&ndash;<el-checkbox v-model="formModel.rules">i管车车贷APP</el-checkbox>&ndash;&gt;-->
				<!--<el-checkbox-group v-model="formModel.rules" :disabled="isValidate ? false : true">-->
				  <!--<el-checkbox label="1">i管车车贷APP</el-checkbox>-->
				<!--</el-checkbox-group>-->
			  <!--</el-form-item>-->
			<!--</el-col>-->
		  <!--</el-row>-->

		  <el-row>

			<!--<el-form-item label="地址" :prop="isValidate ? 'area' : ''">
			  <fns-cascader ref='cascader' :cascaderData="cascaderData" @cascaderChange="cascaderChange" @cascaderBlur="cascaderBlur"></fns-cascader>
			</el-form-item>
-->
			<el-form-item label="地址" :prop="isValidate ? 'area' : ''">
			  <el-cascader
					  placeholder=" 请选择或搜索地址"
					  v-model="formModel.area"
					  :options="addressOption"
					  filterable
					  :props="propData"
					  :clearable="isValidate ? true : false"
					  :disabled="isValidate ? false : true"
					  change-on-select>
			  </el-cascader>
			</el-form-item>

			<el-form-item :offset="1" label="状态" :prop="isValidate ? 'status' : ''">
			  <el-radio-group v-model="formModel.status" :disabled="isValidate ? false : true" >
				<div v-if="isValidate === true">
				  <el-radio :label="1">启用</el-radio>
				  <el-radio :label="0">停用</el-radio>
				</div>
				<div v-else>
				  <el-radio :label="1" >启用</el-radio>
				  <el-radio :label="0" >停用</el-radio>
				</div>
			  </el-radio-group>
			</el-form-item>
		  </el-row>

		  <el-row>
			  <el-form-item class="wid-md" label="详细地址" :prop="isValidate ? 'address' : ''">
			  <el-input v-model="formModel.address" :maxlength="50" type="textarea" placeholder="地址请详细到街道名称、门牌号码号等信息" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true"></el-input>
			  </el-form-item>
		  </el-row>

		  <el-row>
			  <el-form-item class="wid-md" label="描述" >
				<el-input v-model="formModel.description" :maxlength="200" :clearable="isValidate ? true : false" :disabled="isValidate ? false : true" type="textarea" :rows="2" :placeholder="isValidate ? '请输入您的描述' : ''" ></el-input>
			  </el-form-item>
		  </el-row>

		</el-form>
	  </fns-dialog>
	</div>
	<!--重置/删除/停用弹窗-->
	<fns-dialog :dialogData="moreData" @submitForm="submitForm" width="100%" class="fns-model-center">
	  <div slot="body" style="margin-top: 10px;text-align: center;">
		<span class="iconfont icon-wenhao" style="color: red;"></span>
		<span v-if = 'moreData.title === "删除"'>你确定要删除此账号吗？</span>
	  </div>
	</fns-dialog>
  </div>
</template>

<script>
  import { formaterTableData, initScrollTop, clearForm } from '@/utils/publicMethod'
  import * as api from '@/api/system/tenantMng'
  import pages from '@/components/common/page' // 分页
  import fnsHeader from '@/components/common/header' // 头部
  import fnsDialog from '@/components/common/dialog' // lg 780px弹窗
  import fnsTable from '@/components/common/table' // 表格
  import fnsCascader from '@/components/common/cascader' // 级联
  import * as validate from '@/utils/validate' // 验证
  import { mapState } from 'vuex'

  export default {
  	name: 'Tenant',
	data() {
	  var confirmPsd = (rule, value, callback) =>{
		if (value !== this.formModel.password) {
		  callback(new Error('输入密码不一致!'));
		} else {
		  callback()
		}
	  };
	  var psd = (rule, value, callback) =>{
		if (this.formModel.confirmPsd !== '') {
		  this.$refs['formModel'].validateField('confirmPsd');
		}
		callback()
	  };
	  return {
	    id: '',
	    isLoginName: false,
	    islook: false,
		isValidate: false,
		loading: false,
		total: 0,
		addressOption: [],
		propData: {
		  label: 'name',
		  value: 'code'
		},
		cascaderData: {
		  cascader: [],
		  isValidate: false,
		  area: [] // 默认值
		},
		page: {
		  index: 1,
		  size: 10
		},
		header: { // 头部
		  loginName: '',
		  tenantName: '',
		  status: ''
		},
		dialogData: { // 弹窗
		  title: '',
		  dialogVisible: false,
		  size: 'md', // lg, md , sm
		  btnLeft: '取 消',
		  btnRight: '提 交',
		  showBackBtn: false,
		},
		moreData: {
		  title: '',
		  dialogVisible: false,
		  size: 'sm', // lg, md , sm
		  btnLeft: '取 消',
		  btnRight: '确 定',
		},
		customerField: { // 自定义表格字段
		  tableData: [],
		  loading: false,
		  allField: [
			{
			  label: '序号',
			  align: 'center',
			  width: '80',
			  type: 'index'
			},
			{
			  prop: 'loginName',
			  label: '登录名',
			  formatter: this.formatterSaleMode,
			  align: 'center'
			},
			{
			  prop: 'tenantName',
			  label: '租户名称',
			  formatter: this.formatterSaleMode,
			  align: 'center'
			},
			{
			  prop: 'tenantLeader',
			  label: '租户负责人',
			  align: 'center'
			},
			{
			  prop: 'phone',
			  label: '手机号',
			  align: 'center'
			},
			{
			  prop: 'status',
			  label: '状态',
			  align: 'center',
			  formatter: this.formatterStatus,
			},
			{
			  prop: 'createdOn',
			  label: '创建时间',
			  align: 'center'
			}
		  ]
		},
		formModel: {
	      status: 1,
		  password: '',
		  confirmPsd: '',
		  loginName: '',
		  tenantName: '',
		  tenantLeader: '',
		  phone: '',
		  area: [],
		  address: '',
		  description: ''
		},
		tableData: [],
		rules: {
		  status: [
			validate.change()
		  ],
		  password: [
			validate.blur(),
			validate.psd,
			{ validator: psd, trigger: 'blur' },
		  ],
		  confirmPsd: [
			validate.blur(),
			validate.psd,
			{ validator: confirmPsd, trigger: 'blur' },
		  ],
		  loginName: [
			validate.userName,
			validate.blur(),
			validate.nameLength(4 , 16, '长度为 4 到 16')
		  ],
		  tenantName: [
			validate.noSpace,
			validate.blur()
		  ],
		  tenantLeader: [
			validate.noSpace,
			validate.blur()
		  ],
		  phone: [
			validate.blur(),
			validate.phone
		  ],
		  area: [
			validate.blur(),
			validate.change()
		  ],
		  address: [
			validate.blur()
		  ],
		}
	  }
	},
	components: {
	  pages,
	  fnsHeader,
	  fnsTable,
	  fnsDialog,
	  fnsCascader
	},
	watch: {
      ['formModel.address'] (val) { // 监听对象属性
	  },
	  ['dialogData.dialogVisible'] (val) {
        if (!val) {
		  if (this.$refs['formModel'] !== undefined) { // 重置表单及移除验证
			this.$refs['formModel'].resetFields()
		  }
		}
	  }
	},
	created() {
	  this.queryList()
	   this.getAddress()
	},
	computed: {
	  ...mapState({
		stateOption: state => state.selected.state
	  })
	},
	mounted() {
	},
	methods: {
	  // 获取地址
	  getAddress() {
		api.address().then((res) => {
		  if(+res.code === 0) {
			this.addressOption = res.data.children
		  }
		})
	  },
	  cascaderChange (val) {
		this.formModel.area = val.map((item, index) => {
		  return Number(item)
		})
		this.formModel.area[0] = this.formModel.area[0] || '';
		this.formModel.area[1] = this.formModel.area[1] || '';
		this.formModel.area[2] = this.formModel.area[2] || '';
		return this.formModel.area
	  },
	  _pageChange(val, flag) {
		var arr = []
		if (flag === 'size') {
		  this.page.index = val
		  this.queryList('page')
		} else {
		  arr.push(val)
		  this.page.index = 1
		  this.page.size = arr[0]
		  this.queryList('page')
		}
	  },
	  // 打开修改、新增、查看弹窗
	  updateAndAdd(res, name) {
		this.dialogData.title =  name === 'add' ? '新增租户信息' :  name === 'update' ? '修改租户信息' : name === 'look' ? '查看租户信息' : ''
		this.dialogData.dialogVisible = true;
		let id = res ? res.row.id : ''
		this.id = id;
		initScrollTop('formModel') // 滚动条top=0
		if ( name === 'add') {
		  clearForm(this.formModel); // 清空数据
		  this.formModel.status = 1
		  this.dialogData.showBackBtn = false
		  this.isValidate = true
		  this.isLoginName = false
		} else if (name === 'update') { // 修改
		  this.dialogData.showBackBtn = false
		  this.isValidate = true
		  this.isLoginName = true
		  this.look(id)
		} else {
		  this.dialogData.showBackBtn = true
		  this.isValidate = false // 是否验证
		  this.isLoginName = false
		  this.look(id)
		}
	  },
	  // 打开删除、重置密码、停用弹窗
	  openModel(res, name) {
		var data = res.row
		this.moreData.dialogVisible = true
		this.moreData.title =  name === 'delete' ? '删除' :  name === 'reset' ? '重置' : name === 'stop' ? '停用' : ''
		if (name === 'delete') {
		}
	  },
	  add() {
		let addData = {
		  address: this.formModel.address,
		  area: this.cascaderChange(this.formModel.area),
		  description: this.formModel.description,
		  password: this.formModel.password  === '1@0c9x' ? '******' : this.formModel.password,
		  phone: this.formModel.phone,
		  status: this.formModel.status,
		  tenantLeader: this.formModel.tenantLeader,
		  tenantName: this.formModel.tenantName,
		  loginName: this.formModel.loginName
		};

		api.add(addData).then((res) => {
		  if(+res.code === 0) {
			this.queryList()
			this.page.index = 1
			this.dialogData.dialogVisible = false

		  } else {
			this.formModel.confirmPsd = this.formModel.password === '******' ? '1@0c9x' : this.formModel.password
		  }
		}).catch(() => {
		   this.formModel.confirmPsd = this.formModel.password === '******' ? '1@0c9x' : this.formModel.password
		})
	  },
	  look(ids) {
	  	this.loading = true
		api.look({ id: ids }).then((res) => {
		 if(+res.code === 0) {
		   this.formModel = { ...res.data };
		   this.formModel.password = this.formModel.confirmPsd = '1@0c9x'
		   // 地址级联赋默认值
		   let arr = this.formModel.area.map((item, index) => {
			 return Number(item)
		   })
		   this.formModel.area = arr
		   if (this.$refs['formModel'] !== undefined) { // 重置表单及移除验证
			 this.$refs['formModel'].resetFields()
		   }
		 }
		 this.loading = false
		})
	  },
	  updateEvent() {

		let updateData = {
		  address: this.formModel.address,
		  area: this.cascaderChange(this.formModel.area),
		  description: this.formModel.description,
		  password: this.formModel.password  === '1@0c9x' ? '******' : this.formModel.password,
		  phone: this.formModel.phone,
		  status: this.formModel.status,
		  tenantLeader: this.formModel.tenantLeader,
		  tenantName: this.formModel.tenantName,
		  userId: this.formModel.userId
		};

		api.update(updateData, this.id).then((res) => {
		  if(+res.code === 0) {
			this.queryList()
			this.dialogData.dialogVisible = false
		  }
		  this.formModel.confirmPsd = this.formModel.password === '******' ? '1@0c9x' : this.formModel.password
		}).catch(() => {
		  this.formModel.confirmPsd = this.formModel.password === '******' ? '1@0c9x' : this.formModel.password
		})
	  },
	  delete() {
	  },
	  // dialog提交
	  submitForm(val) {
		if (val === '修改租户信息') {
		  this.$refs['formModel'].validate((valid) => {
			if (valid) {
			  this.updateEvent()
			}
		  })
		} else if (val === '新增租户信息') {
		  this.$refs['formModel'].validate((valid) => {
			console.log('add', valid)
			if (valid) {
			  this.add()
			  this.queryList()
			  this.page.index = 1

			}
		  })
		} else if (val === '删除') {
		  this.delete()
		}
	  },
	  // 搜索、查询
//	  queryList(params) {
//		this.customerField.loading = true
//		var data = {}
//		if(params === 'search') {
//		  data = Object.assign({}, this.header, { index: 1, size: this.page.size })
//		} else if(params === 'page') {
//		  data = Object.assign({}, this.header, { index: this.page.index, size: this.page.size })
//		} else {
//		  data = { index: this.page.index, size: this.page.size }
//		}
//		api.list(data).then((res) => {
//		  if (+res.code === 0) {
//			this.customerField.tableData = formaterTableData(res.data.rows) // 格式化表格数据
//			this.total = +res.data.total
//		  } else {
//			this.customerField.tableData = []
//		  }
//		   this.customerField.loading = false
//		}).catch(() => {
//		   this.customerField.loading = false
//		})
//	  },
	  queryList() {
		this.customerField.loading = true
		let pages = {
		  index: this.page.index,
		  size: this.page.size
		}
		let data = Object.assign({}, this.header, pages)
		api.list(data).then((res) => {
		  // this.tableData = formaterTableData(res.data.rows) // 格式化表格数据
		  this.customerField.tableData = res.data.rows
		  this.total = +res.data.total
		  this.customerField.tableData.map((item, index) => {
			for (var i in item) {
			  if (item[i] === null || '') {
				item[i] = ' '
			  }
			}
		  })
		  this.customerField.loading = false
		}).catch(() => {
		  this.customerField.loading = false
		})
	  },
	  formatterStatus(row) {
		if(+row.status === 1) {
	      return '启用'
		} else {
	      return '停用'
		}
	  }
	}
  }
</script>
<style lang="scss">
  .systemAgent {
	.el-cascader {
	  width: 100%;
	}
  }
</style>


